package tsli.acm.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import tsli.acm.biz.AgentDebtManagement;
import tsli.acm.dao.GAAgentStructureDAO;
import tsli.acm.dao.SFCAgentStructureDAO;
import tsli.acm.dao.SFCCommissionNegativeDAO;
import tsli.acm.dao.SFCCommissionPositiveDAO;
import tsli.acm.database.Database;
import tsli.acm.model.SFCCommissionPositive;


public class ACM1201Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

    public ACM1201Srvl() {
        super();

    }
    
    public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	
    	if (request.getParameter("process_type").equals("getDataTable")) {
			getDataTable(request, response);
		} else if (request.getParameter("process_type").equals("getCalculateData")) {
			getCalculateData(request, response);
		} else if (request.getParameter("process_type").equals("getDataDetailTable")){
			getDataDetailTable(request, response);
		}
    }
    
    public void getDataTable(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	
    	int vnStart = Integer.parseInt(request.getParameter("iDisplayStart")); // 0
    	int vnAmount = Integer.parseInt(request.getParameter("iDisplayLength")); // 10
    	String vaDraw = request.getParameter("sEcho");
    	String vaMonth = request.getParameter("sSearch_0").trim();
    	String vaYear = request.getParameter("sSearch_1").trim();

    	// get data from database
    	int vnTotal = 0;
    	int vnTotalAfterFilter = 0;
    	List<Map<String, String>> voResult =  new ArrayList<Map<String, String>>();


    	Database db = new Database();
    	SFCAgentStructureDAO voSFCAgentStructure = new SFCAgentStructureDAO(db);
    	List<Map<String, Object>> vaVPInfo = voSFCAgentStructure.findSFCAgent(vaYear+""+vaMonth);
    	
    	try {
    	   	vnTotal = vaVPInfo.size();
    		if (vnAmount == -1) {
    			for (int i = 0; i < vaVPInfo.size(); i++) {

    				Map<String, String> voTmp = new HashMap<String, String>();
    				voTmp.put("PE_NO", vaVPInfo.get(i).get("PE_NO").toString());
    				voTmp.put("TITLE_NAME", vaVPInfo.get(i).get("NM_TITLE_THAI").toString());
    				voTmp.put("NAME", vaVPInfo.get(i).get("NM_THAI").toString());
    				voTmp.put("SURNAME", vaVPInfo.get(i).get("SURNM_THAI").toString());
    				voResult.add(voTmp);
    			}
    		    vnTotalAfterFilter = vnTotal;
    		} else {
    			if (vaVPInfo.size() != 0) {
    				for (int i = vnStart; i < (vnStart + vnAmount); i++) {

    					Map<String, String> voTmp = new HashMap<String, String>();
    					voTmp.put("PE_NO", vaVPInfo.get(i).get("PE_NO").toString());
        				voTmp.put("TITLE_NAME", vaVPInfo.get(i).get("NM_TITLE_THAI").toString());
        				voTmp.put("NAME", vaVPInfo.get(i).get("NM_THAI").toString());
        				voTmp.put("SURNAME", vaVPInfo.get(i).get("SURNM_THAI").toString());
    					voResult.add(voTmp);
    					if (i == (vaVPInfo.size() - 1)) 
    						break;
    				}
    			}
    			vnTotalAfterFilter = vnTotal;
    		}
    	} finally {
    		db.close();
    	}  
    	// prepare data to show in dataTable
    	PrintWriter voOut = response.getWriter();
    	// set sequence
    	int[] vnSequence = new int[voResult.size()];
    	for (int i = 1; i <= voResult.size(); i++)
    		vnSequence[i - 1] = i + vnStart;
    	try {
    	   	JSONObject voObject = new JSONObject();
    	    JSONArray voListData = new JSONArray();
    	    for (int i = 0; i < voResult.size(); i++) {
    	    	Map<String, String> voTmp = voResult.get(i);	
    			JSONArray voArray = new JSONArray();
    			voArray.add(vnSequence[i]);
    			voArray.add(voTmp.get("PE_NO"));
    			voArray.add((voTmp.get("TITLE_NAME") + " " + voTmp.get("NAME") + " " + voTmp.get("SURNAME")));
    			voArray.add(getFAReal(voTmp.get("PE_NO"),vaYear+""+vaMonth));
    			// data for button's action
    			String paName = (voTmp.get("TITLE_NAME") + " " + voTmp.get("NAME") + " " + voTmp.get("SURNAME"));
    			String paData = voTmp.get("PE_NO").toString()+","+paName+","+vaMonth+","+vaYear;

    			voArray.add(paData);
    			// adding array data into list
    		    voListData.add(voArray);
    		}
    		voObject.put("sEcho", Integer.parseInt(vaDraw));
    		voObject.put("iTotalRecords", vnTotal);
    		voObject.put("iTotalDisplayRecords", vnTotalAfterFilter);
    		voObject.put("aaData", voListData);
    		voOut.print(voObject.toJSONString());
    	} finally {
    			voOut.close();
    	}
    }
    
    public void getDataDetailTable(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	
    	int vnStart = Integer.parseInt(request.getParameter("iDisplayStart")); // 0
    	int vnAmount = Integer.parseInt(request.getParameter("iDisplayLength")); // 10
    	String vaDraw = request.getParameter("sEcho");
    	String vaPeNo = request.getParameter("sSearch_0").trim();
    	String vaClosYm = request.getParameter("sSearch_1").trim();
    	String vaType = request.getParameter("sSearch_2").trim();

    	// get data from database
    	int vnTotal = 0;
    	int vnTotalAfterFilter = 0;
    	List<Map<String, String>> voResult =  new ArrayList<Map<String, String>>();


    	Database db = new Database();
    	SFCCommissionPositiveDAO voSFCCommissionPositive = new SFCCommissionPositiveDAO(db);
    	List<Map<String, Object>> vaGAInfo = null;
    	if(vaType.equals("getPCDetail")){
    		vaGAInfo = voSFCCommissionPositive.getPCPositiveDetail(vaPeNo, vaClosYm);
    	}else{
    		vaGAInfo = voSFCCommissionPositive.getPCNegativeDetail(vaPeNo, vaClosYm);
    	}

    	
    	try {
    	   	vnTotal = vaGAInfo.size();
    		if (vnAmount == -1) {
    			for (int i = 0; i < vaGAInfo.size(); i++) {

    				Map<String, String> voTmp = new HashMap<String, String>();
    				voTmp.put("CLOS_YM", vaGAInfo.get(i).get("CLOS_YM").toString());
    				voTmp.put("PE_NO_COL", vaGAInfo.get(i).get("PE_NO_COL").toString());
    				voTmp.put("PO_NO", vaGAInfo.get(i).get("PO_NO").toString());
    				voTmp.put("AFYP", vaGAInfo.get(i).get("AFYP").toString());
    				voTmp.put("ARYP2", vaGAInfo.get(i).get("ARYP2").toString());
    				voTmp.put("PC", vaGAInfo.get(i).get("PC").toString());
    				voResult.add(voTmp);
    			}
    		    vnTotalAfterFilter = vnTotal;
    		} else {
    			if (vaGAInfo.size() != 0) {
    				for (int i = vnStart; i < (vnStart + vnAmount); i++) {

    					Map<String, String> voTmp = new HashMap<String, String>();
    					voTmp.put("CLOS_YM", vaGAInfo.get(i).get("CLOS_YM").toString());
        				voTmp.put("PE_NO_COL", vaGAInfo.get(i).get("PE_NO_COL").toString());
        				voTmp.put("PO_NO", vaGAInfo.get(i).get("PO_NO").toString());
        				voTmp.put("AFYP", vaGAInfo.get(i).get("AFYP").toString());
        				voTmp.put("ARYP2", vaGAInfo.get(i).get("ARYP2").toString());
        				voTmp.put("PC", vaGAInfo.get(i).get("PC").toString());
    					voResult.add(voTmp);
    					if (i == (vaGAInfo.size() - 1)) 
    						break;
    				}
    			}
    			vnTotalAfterFilter = vnTotal;
    		}
    	} finally {
    		db.close();
    	}  
    	
    	DecimalFormat voDecimalFormat = new DecimalFormat("#,##0.00");
    	// prepare data to show in dataTable
    	PrintWriter voOut = response.getWriter();
    	// set sequence
    	int[] vnSequence = new int[voResult.size()];
    	for (int i = 1; i <= voResult.size(); i++)
    		vnSequence[i - 1] = i + vnStart;
    	try {
    	   	JSONObject voObject = new JSONObject();
    	    JSONArray voListData = new JSONArray();
    	    for (int i = 0; i < voResult.size(); i++) {
    	    	Map<String, String> voTmp = voResult.get(i);	
    			JSONArray voArray = new JSONArray();
    			voArray.add(vnSequence[i]);
    			voArray.add(voTmp.get("CLOS_YM"));
    			voArray.add(voTmp.get("PE_NO_COL"));
    			voArray.add(voTmp.get("PO_NO"));
    			voArray.add(voDecimalFormat.format(Double.parseDouble(voTmp.get("AFYP"))));
    			voArray.add(voDecimalFormat.format(Double.parseDouble(voTmp.get("ARYP2"))));
    			voArray.add(voDecimalFormat.format(Double.parseDouble(voTmp.get("PC"))));
    			// adding array data into list
    		    voListData.add(voArray);
    		}
    		voObject.put("sEcho", Integer.parseInt(vaDraw));
    		voObject.put("iTotalRecords", vnTotal);
    		voObject.put("iTotalDisplayRecords", vnTotalAfterFilter);
    		voObject.put("aaData", voListData);
    		voOut.print(voObject.toJSONString());
    	} finally {
    			voOut.close();
    	}
    }
    
	public void getCalculateData(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		String vaPeNo = request.getParameter("peNo");
		String vaMonth = request.getParameter("month");
		String vaYear = request.getParameter("year");
		
		String vaClosYm = vaYear+vaMonth;
		
		List<SFCCommissionPositive> voSFCCommissionPositive = new ArrayList<SFCCommissionPositive>();
		Database db = new Database();
		SFCCommissionPositiveDAO voSFCCommissionPositiveDAO = new SFCCommissionPositiveDAO(db);
		SFCCommissionNegativeDAO voSFCCommissionNegativeDAO = new SFCCommissionNegativeDAO(db);
		
		PrintWriter out = response.getWriter();
		
		try {
			List<Map<String, Object>> voSFCComPoResult = null;
			String vnPCPositive = voSFCCommissionPositiveDAO.getPCPositive(vaPeNo, vaClosYm);
			String vnPCNegative = voSFCCommissionPositiveDAO.getPCNegative(vaPeNo, vaClosYm);
			voSFCComPoResult  = voSFCCommissionPositiveDAO.findcalculateFA(vnPCPositive,vnPCNegative,vaClosYm,vaPeNo);
			// get standard_activity.bizrt_itm_amt (% payment)

			double vnSaAmt = Double.parseDouble(voSFCComPoResult.get(0).get("BIZRT_ITM_AMT").toString());
			AgentDebtManagement voADM = new AgentDebtManagement();
			if(voSFCComPoResult.size() == 0){
				JSONObject voObject = new JSONObject();
				voObject.put("type", "empty");
				
				out.print(voObject.toJSONString());
				return;
			}else{
				int vnThisMonth = Integer.parseInt(vaClosYm);
				int vnBeforeOneMonth = Integer.parseInt(vaClosYm)-1;
				int vnBeforeTwoMonth = Integer.parseInt(vaClosYm)-2;

				String vnPCPositiveThisMonth = voSFCCommissionPositiveDAO.getPCPositive(vaPeNo, vnThisMonth+"");
				String vnPCNegativeThisMonth = voSFCCommissionPositiveDAO.getPCNegative(vaPeNo, vnThisMonth+"");
				
				String vnPCPositiveBeforeOneMonth = voSFCCommissionPositiveDAO.getPCPositive(vaPeNo, vnBeforeOneMonth+"");
				String vnPCNegativeBeforeOneMonth = voSFCCommissionPositiveDAO.getPCNegative(vaPeNo, vnBeforeOneMonth+"");
				
				String vnPCPositiveBeforeTwoMonth = voSFCCommissionPositiveDAO.getPCPositive(vaPeNo, vnBeforeTwoMonth+"");
				String vnPCNegativeBeforeTwoMonth = voSFCCommissionPositiveDAO.getPCNegative(vaPeNo, vnBeforeTwoMonth+"");
				
				
				String vaPersisRate[]  = {"","100","99","98","97","96","95","94","93","92","91","90","89"};
				String vaEncoMMS = voSFCComPoResult.get(0).get("FST_ENCO_MMS").toString();
				if (vaEncoMMS.equals("3") || vaEncoMMS.equals("6") || vaEncoMMS.equals("9") || vaEncoMMS.equals("12")) {
					voSFCComPoResult = voSFCCommissionPositiveDAO.findcalculateFAReCAl(vaClosYm,vaPeNo);
					
					JSONObject voObject = new JSONObject();
					
					DecimalFormat voDecimalFormat = new DecimalFormat("#,##0.00");
					
					int vnEncoMMS = Integer.parseInt(vaEncoMMS);
					voObject.put("this_month", vnEncoMMS);
					voObject.put("before_one_month", (vnEncoMMS-1));
					voObject.put("before_two_month", (vnEncoMMS-2));
					
					//THIS MONTH
					voObject.put("pc", voDecimalFormat.format(Double.parseDouble(vnPCPositiveThisMonth)));
					voObject.put("free_look", voDecimalFormat.format(Double.parseDouble(vnPCNegativeThisMonth)));
					voObject.put("freelook_cal",voDecimalFormat.format(Double.parseDouble(voSFCCommissionNegativeDAO.getFreeLookTotal(vaPeNo, vnPCPositiveThisMonth))));
					voObject.put("freelook_total",voDecimalFormat.format(Double.parseDouble(voSFCComPoResult.get(0).get("FA_TOTAL").toString())-Double.parseDouble(voSFCCommissionNegativeDAO.getFreeLookTotal(vaPeNo, vnPCPositiveThisMonth))));
					voObject.put("pc_total", voDecimalFormat.format(Double.parseDouble(voSFCComPoResult.get(0).get("PC").toString())));
					voObject.put("fa", voDecimalFormat.format(Double.parseDouble(voSFCComPoResult.get(0).get("FA").toString())));
					voObject.put("fa_total", voDecimalFormat.format(Double.parseDouble(voSFCComPoResult.get(0).get("FA_TOTAL").toString())));
					voObject.put("persistency", voSFCComPoResult.get(0).get("PERSISTENCY_RATE").toString());
					voObject.put("persistency_rate", vaPersisRate[vnEncoMMS]);
					if(voSFCComPoResult.get(0).get("BIZRT_ITM_DATA").toString().equals("Y")){
						voObject.put("status", "ผ่าน");
					}else{
						voObject.put("status", "ไม่ผ่าน");
					}
					
					//BEFORE ONE MONTH
					voObject.put("pc_before_one_month", voDecimalFormat.format(Double.parseDouble(vnPCPositiveBeforeOneMonth)));
					voObject.put("free_look_before_one_month", voDecimalFormat.format(Double.parseDouble(vnPCNegativeBeforeOneMonth)));
					voObject.put("freelookcal_before_one_month",voDecimalFormat.format(Double.parseDouble(voSFCCommissionNegativeDAO.getFreeLookTotal(vaPeNo, vnPCNegativeBeforeOneMonth))));
					voObject.put("freelooktotal_before_one_month",voDecimalFormat.format(Double.parseDouble(voSFCComPoResult.get(0).get("FA_TOTAL_BEFORE_ONE").toString())-Double.parseDouble(voSFCCommissionNegativeDAO.getFreeLookTotal(vaPeNo, vnPCNegativeBeforeOneMonth))));
					voObject.put("pc_total_before_one_month", voDecimalFormat.format(Double.parseDouble(voSFCComPoResult.get(0).get("PC_BEFORE_ONE").toString())));
					voObject.put("fa_before_one_month", voDecimalFormat.format(Double.parseDouble(voSFCComPoResult.get(0).get("FA_BEFORE_ONE").toString())));
					voObject.put("fa_total_before_one_month", voDecimalFormat.format(Double.parseDouble(voSFCComPoResult.get(0).get("FA_TOTAL_BEFORE_ONE").toString())));
					voObject.put("persistency_before_one_month", voSFCComPoResult.get(0).get("PERSISTENCY_RATE_BEFORE_ONE").toString());
					voObject.put("persistency_rate_before_one_month", vaPersisRate[vnEncoMMS-1]);
					if(voSFCComPoResult.get(0).get("BIZRT_ITM_DATA_BEFORE_ONE").toString().equals("Y")){
						voObject.put("status_before_one_month", "ผ่าน");
					}else{
						voObject.put("status_before_one_month", "ไม่ผ่าน");
					}
					
					//BEFORE TWO MONTH
					voObject.put("pc_before_two_month", voDecimalFormat.format(Double.parseDouble(vnPCPositiveBeforeTwoMonth)));
					voObject.put("free_look_before_two_month", voDecimalFormat.format(Double.parseDouble(vnPCNegativeBeforeTwoMonth)));
					voObject.put("freelookcal_before_two_month",voDecimalFormat.format(Double.parseDouble(voSFCCommissionNegativeDAO.getFreeLookTotal(vaPeNo, vnPCNegativeBeforeTwoMonth))));
					voObject.put("freelooktotal_before_two_month",voDecimalFormat.format(Double.parseDouble(voSFCComPoResult.get(0).get("FA_TOTAL_BEFORE_TWO").toString())-Double.parseDouble(voSFCCommissionNegativeDAO.getFreeLookTotal(vaPeNo, vnPCNegativeBeforeTwoMonth))));
					voObject.put("pc_total_before_two_month", voDecimalFormat.format(Double.parseDouble(voSFCComPoResult.get(0).get("PC_BEFORE_TWO").toString())));
					voObject.put("fa_before_two_month", voDecimalFormat.format(Double.parseDouble(voSFCComPoResult.get(0).get("FA_BEFORE_TWO").toString())));
					voObject.put("fa_total_before_two_month", voDecimalFormat.format(Double.parseDouble(voSFCComPoResult.get(0).get("FA_TOTAL_BEFORE_TWO").toString())));
					voObject.put("persistency_before_two_month", voSFCComPoResult.get(0).get("PERSISTENCY_RATE_BEFORE_TWO").toString());
					voObject.put("persistency_rate_before_two_month", vaPersisRate[vnEncoMMS-2]);
					if(voSFCComPoResult.get(0).get("BIZRT_ITM_DATA_BEFORE_TWO").toString().equals("Y")){
						voObject.put("status_before_two_month", "ผ่าน");
					}else{
						voObject.put("status_before_two_month", "ไม่ผ่าน");
					}

					double vnSumPCTotal = Double.parseDouble(voSFCComPoResult.get(0).get("PC").toString())+
							Double.parseDouble(voSFCComPoResult.get(0).get("PC_BEFORE_ONE").toString())+
							Double.parseDouble(voSFCComPoResult.get(0).get("PC_BEFORE_TWO").toString());
					
					double vnSumFA = Double.parseDouble(voSFCComPoResult.get(0).get("FA").toString())+
					Double.parseDouble(voSFCComPoResult.get(0).get("FA_BEFORE_ONE").toString())+
					Double.parseDouble(voSFCComPoResult.get(0).get("FA_BEFORE_TWO").toString());
					
					voObject.put("sumpc", voDecimalFormat.format(Double.parseDouble(vnPCPositiveThisMonth)+
							Double.parseDouble(vnPCPositiveBeforeOneMonth)+
							Double.parseDouble(vnPCPositiveBeforeTwoMonth)));
					voObject.put("sumfreelook", voDecimalFormat.format(Double.parseDouble(vnPCNegativeThisMonth)+
							Double.parseDouble(vnPCNegativeBeforeOneMonth)+
							Double.parseDouble(vnPCNegativeBeforeTwoMonth)));
					voObject.put("sumpctotal", voDecimalFormat.format(vnSumPCTotal));
					voObject.put("sumfa", voDecimalFormat.format(vnSumFA));
					voObject.put("sumfatotal", voDecimalFormat.format(Double.parseDouble(voSFCComPoResult.get(0).get("FA_TOTAL").toString())+
							Double.parseDouble(voSFCComPoResult.get(0).get("FA_TOTAL_BEFORE_ONE").toString())+
							Double.parseDouble(voSFCComPoResult.get(0).get("FA_TOTAL_BEFORE_TWO").toString())));
					
					double vnFACal = Double.parseDouble(voSFCComPoResult.get(0).get("FA_CAL").toString());
					voObject.put("pcRecal", voDecimalFormat.format(vnSumPCTotal)+" / 3 = "+voDecimalFormat.format(vnSumPCTotal/3)+" (เฉลี่ย)");
					voObject.put("faShowCal",voDecimalFormat.format(vnFACal)+" + "
										+voDecimalFormat.format(vnFACal)+" + "
										+voDecimalFormat.format(vnFACal)+"<br>"+
									" = "+voDecimalFormat.format(vnFACal*3)+" - "+voDecimalFormat.format(vnSumFA));
					double vnShowRecal = (vnFACal*3)-vnSumFA;
					if(vnShowRecal<0){
						vnShowRecal = 0;
					}
					if(voSFCComPoResult.get(0).get("BIZRT_ITM_DATA").toString().equals("Y")){
						voObject.put("faShowReCal",voDecimalFormat.format(vnShowRecal));
					}else{
						voObject.put("faShowReCal","<s>"+voDecimalFormat.format(vnShowRecal)+"</s>");
					}
					// agent debt
					double vnBonus = (Double.parseDouble(voSFCComPoResult.get(0).get("FA_TOTAL").toString()));
					if (((vnFACal*3)-vnSumFA) < 0) {
						vnBonus = vnSumFA;
					} else if(voSFCComPoResult.get(0).get("BIZRT_ITM_DATA").toString().equals("Y")){
						vnBonus += ((vnFACal*3)-vnSumFA);
					}
					double vnPayment = (vnSaAmt * 0.01) * vnBonus;
					String vaMessage = "เปอร์เซ็นการจ่ายเงินจาก Stardard Activity = " + voDecimalFormat.format(vnSaAmt) 
							+ "% โดยจ่ายเงินค่า FA: " + voDecimalFormat.format((Double.parseDouble(voSFCComPoResult.get(0).get("FA_TOTAL").toString())+vnShowRecal)*(vnSaAmt * 0.01)) + " บาท";
					double[] vnTmp = {vnPayment};
					
					voObject.put("message", vaMessage);
					
					voObject.put("type", "catchup");
					
					voObject.put("peno", vaPeNo);
					voObject.put("closym", vnThisMonth);
					voObject.put("closym_before_one", vnBeforeOneMonth);
					voObject.put("closym_before_two", vnBeforeTwoMonth);
					
					out.print(voObject.toJSONString());
					return;
				}else{
					int vnEncoMMS = Integer.parseInt(vaEncoMMS);
					JSONObject voObject = new JSONObject();
					
					DecimalFormat voDecimalFormat = new DecimalFormat("#,##0.00");
					
					voObject.put("month", voSFCComPoResult.get(0).get("FST_ENCO_MMS").toString());
					voObject.put("free_look", voDecimalFormat.format(Double.parseDouble(vnPCNegative)));
					voObject.put("freelookcal",voDecimalFormat.format(Double.parseDouble(voSFCCommissionNegativeDAO.getFreeLookTotal(vaPeNo, vaClosYm))));
					voObject.put("freelooktotal",voDecimalFormat.format(Double.parseDouble(voSFCComPoResult.get(0).get("FA_TOTAL").toString())-Double.parseDouble(voSFCCommissionNegativeDAO.getFreeLookTotal(vaPeNo, vaClosYm))));
					voObject.put("pc_total", voDecimalFormat.format(Double.parseDouble(voSFCComPoResult.get(0).get("PC").toString())));
					voObject.put("pc", voDecimalFormat.format(Double.parseDouble(vnPCPositive)));
					voObject.put("fa", voDecimalFormat.format(Double.parseDouble(voSFCComPoResult.get(0).get("FA").toString())));
					voObject.put("fa_total", voDecimalFormat.format(Double.parseDouble(voSFCComPoResult.get(0).get("FA_TOTAL").toString())));
					voObject.put("persistency", voSFCComPoResult.get(0).get("PERSISTENCY_RATE").toString());
					voObject.put("persistency_rate", vaPersisRate[vnEncoMMS]);
					if(voSFCComPoResult.get(0).get("BIZRT_ITM_DATA").toString().equals("Y")){
						voObject.put("status", "ผ่าน");
					}else{
						voObject.put("status", "ไม่ผ่าน");
					}
					// agent debt
					voObject.put("peno", vaPeNo);
					voObject.put("closym", vaClosYm);
					double vnPayment = (vnSaAmt * 0.01) * (Double.parseDouble(voSFCComPoResult.get(0).get("FA_TOTAL").toString()));
					String vaMessage = "เปอร์เซ็นการจ่ายเงินจาก Stardard Activity = " + voDecimalFormat.format(vnSaAmt) 
							+ "% โดยจ่ายเงินค่า FA: " + voDecimalFormat.format((Double.parseDouble(voSFCComPoResult.get(0).get("FA_TOTAL").toString())*(vnSaAmt * 0.01))) + " บาท";
					double[] vnTmp = {vnPayment};
					
					voObject.put("message", vaMessage);
					
					voObject.put("type", "inmonth");					
					out.print(voObject.toJSONString());					
					return;
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			out.close();
			db.close();
		}
		
		
	}
	
	public String getFAReal(String paPeNo, String paClosYm){
		String vaPeNo = paPeNo;
		String vaClosYm = paClosYm;
		
		String vaFaReal = "";
		
		List<SFCCommissionPositive> voSFCCommissionPositive = new ArrayList<SFCCommissionPositive>();
		Database db = new Database();
		SFCCommissionPositiveDAO voSFCCommissionPositiveDAO = new SFCCommissionPositiveDAO(db);
		SFCCommissionNegativeDAO voSFCCommissionNegativeDAO = new SFCCommissionNegativeDAO(db);
		DecimalFormat voDecimalFormat = new DecimalFormat("#,##0.00");
	
		
		try {
			List<Map<String, Object>> voSFCComPoResult = null;
			String vnPCPositive = voSFCCommissionPositiveDAO.getPCPositive(vaPeNo, vaClosYm);
			String vnPCNegative = voSFCCommissionPositiveDAO.getPCNegative(vaPeNo, vaClosYm);
			voSFCComPoResult  = voSFCCommissionPositiveDAO.findcalculateFA(vnPCPositive,vnPCNegative,vaClosYm,vaPeNo);
			// get standard_activity.bizrt_itm_amt (% payment)
	
			double vnSaAmt = Double.parseDouble(voSFCComPoResult.get(0).get("BIZRT_ITM_AMT").toString());
			AgentDebtManagement voADM = new AgentDebtManagement();
			if(voSFCComPoResult.size() == 0){
			}else{
				int vnThisMonth = Integer.parseInt(vaClosYm);
				int vnBeforeOneMonth = Integer.parseInt(vaClosYm)-1;
				int vnBeforeTwoMonth = Integer.parseInt(vaClosYm)-2;
	
				String vnPCPositiveThisMonth = voSFCCommissionPositiveDAO.getPCPositive(vaPeNo, vnThisMonth+"");
				String vnPCNegativeThisMonth = voSFCCommissionPositiveDAO.getPCNegative(vaPeNo, vnThisMonth+"");
				
				String vnPCPositiveBeforeOneMonth = voSFCCommissionPositiveDAO.getPCPositive(vaPeNo, vnBeforeOneMonth+"");
				String vnPCNegativeBeforeOneMonth = voSFCCommissionPositiveDAO.getPCNegative(vaPeNo, vnBeforeOneMonth+"");
				
				String vnPCPositiveBeforeTwoMonth = voSFCCommissionPositiveDAO.getPCPositive(vaPeNo, vnBeforeTwoMonth+"");
				String vnPCNegativeBeforeTwoMonth = voSFCCommissionPositiveDAO.getPCNegative(vaPeNo, vnBeforeTwoMonth+"");
				
				
				String vaPersisRate[]  = {"","100","99","98","97","96","95","94","93","92","91","90","89"};
				String vaEncoMMS = voSFCComPoResult.get(0).get("FST_ENCO_MMS").toString();
				if (vaEncoMMS.equals("3") || vaEncoMMS.equals("6") || vaEncoMMS.equals("9") || vaEncoMMS.equals("12")) {
					voSFCComPoResult = voSFCCommissionPositiveDAO.findcalculateFAReCAl(vaClosYm,vaPeNo);
					
					JSONObject voObject = new JSONObject();

					voObject.put("fa_total", voDecimalFormat.format(Double.parseDouble(voSFCComPoResult.get(0).get("FA_TOTAL").toString())));
	
	
					double vnSumPCTotal = Double.parseDouble(voSFCComPoResult.get(0).get("PC").toString())+
							Double.parseDouble(voSFCComPoResult.get(0).get("PC_BEFORE_ONE").toString())+
							Double.parseDouble(voSFCComPoResult.get(0).get("PC_BEFORE_TWO").toString());
					
					double vnSumFA = Double.parseDouble(voSFCComPoResult.get(0).get("FA").toString())+
					Double.parseDouble(voSFCComPoResult.get(0).get("FA_BEFORE_ONE").toString())+
					Double.parseDouble(voSFCComPoResult.get(0).get("FA_BEFORE_TWO").toString());

					double vnFACal = Double.parseDouble(voSFCComPoResult.get(0).get("FA_CAL").toString());
					
					double vnShowRecal = (vnFACal*3)-vnSumFA;
					if(vnShowRecal<0){
						vnShowRecal = 0;
					}
					
					vaFaReal = voDecimalFormat.format(Double.parseDouble(voSFCComPoResult.get(0).get("FA_TOTAL").toString())+vnShowRecal);
					
				}else{
					
					vaFaReal = voDecimalFormat.format(Double.parseDouble(voSFCComPoResult.get(0).get("FA_TOTAL").toString()));
					
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

			db.close();
		}
		
		return vaFaReal;
	}

    public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}

}
